/*Main*/ 
#include "stdafx.h"
#include "SimpleBarrier.h"
#include "cpp_framework.h"
#include <pthread.h>

/*
 * Impl of the pure virtual function.  
 */	
void SimpleBarrier::await() 
{
	int pos = _count.getAndDecrement();

	if (pos == 0)
	{
		//_count.set(_size);
	} else
	{
		while (_count.get() != 0){} 
	}
}

#define NUM_THREADS 8
SimpleBarrier *bar = new SimpleBarrier(NUM_THREADS);
CMDR::AtomicInteger counter;

void *hello(void* arg) {
	int res = counter.getAndDecrement();
	printf("Hello from thread %i\n",res);
	fflush(stdout);
	bar->await();
	return (void*) res;
}

int main(){

	counter.set(NUM_THREADS);

	pthread_t thread[NUM_THREADS];
	
	for (int i=0; i<NUM_THREADS; i++){
		if (pthread_create(&thread[i],NULL,hello,(void*)&i)!=0){
			printf("pthread_create()error");
			exit(99);
		}
	}

	for (int j=0; j<NUM_THREADS; j++){
		printf("join thread number %d, ret: %d\n",j,pthread_join(thread[j],NULL));
		fflush(stdout);
	}

	system("pause");
}
